<template>
  <div class="top_search">
    <a-form layout="vertical" :model="searchForm" style="display: flex">
      <a-form-item label="交易类型" class="form_item">
		<a-cascader :changeOnSelect="true" @change="handleCascaderChange" v-model:value="transitionValue" :options="transitionType" placeholder="请选择" allowClear/>
      </a-form-item>
      <a-form-item label="业务单号" class="form_item">
        <a-input
          placeholder="请输入"
          v-model:value="searchForm.bill_no"
          allowClear
        />
      </a-form-item>
      <a-form-item label="交易时间" style="width: 300px" class="form_item">
        <a-range-picker
          @change="handleDateChange"
          v-model:value="timeRange"
          allowClear
        />
      </a-form-item>
      <a-form-item label="余额类型" class="form_item">
        <a-select
          v-model:value="searchForm.account_type"
          placeholder="请选择"
          :options="balanceType"
          allowClear
        ></a-select>
      </a-form-item>
      

      <a-form-item label=" " class="form_item">
        <a-button type="primary" @click="queryThis('query')">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button
          type="default"
          style="margin-left: 10px"
          @click="queryThis('reset')"
        >
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-form>
  </div>
  <div class="export">
    <a-button :loading="btnloading" type="primary" @click="handleExport">导出</a-button>
  </div>

  <div class="table_con">
    <a-table
      :loading="tableLoading"
      :pagination="pageInfo"
      :dataSource="dataSource"
      :columns="columns"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'account_type'">
          <a-space direction="vertical">
            <span>
              {{ record.module_event }}
            </span>
            <span style="color: #999">
              {{ record.account_type }}
            </span>
          </a-space>
        </template>
        <template v-if="column.key === 'changes'">
          {{ record.changes }} {{ record.unit }}
        </template>
        <template v-if="column.key === 'created_at'">
           {{ convertTimeToTimezone(record.created_at) }}
        </template>
        
        <template v-if="column.key === 'modification'">
          <div>
            交易前：{{ record.pre_balance }} {{ record.unit }}
          </div>
          <div>
            交易后：{{ record.balance }} {{ record.unit }}
          </div>
        </template>
      </template>
    </a-table>
  </div>

  <ExportMdal :visible="visibleExport" @cacel="visibleExport = false" />
</template>

<script>
import { defineComponent, reactive, toRefs, computed,inject } from "vue";
import {
  DownOutlined,
  UpOutlined,
  SearchOutlined,
  ReloadOutlined,
} from "@ant-design/icons-vue";
import dayjs from "dayjs";
import request from "../../../../common/utils/request";
import { message } from "ant-design-vue";
import ExportMdal from "../../../shotstack/components/ExportMdal/index.vue";

const initialParams = {
  /**
   * 余额类型
   */
  account_type: null,
  /**
   * 业务单号
   */
  bill_no: "",
  /**
   * 项目id
   */
  merchant_library_id: null,
  /**
   * 交易类型
   */
  module_event: [],
  /**
   * 交易时间-开始
   */
  start_time: "",
  /**
   * 交易时间-结束
   */
  end_time: "",
};
export default defineComponent({
  name: "transactionFlow",
  components: {
    DownOutlined,
    UpOutlined,
    SearchOutlined,
    ReloadOutlined,
    ExportMdal,
  },
  setup() {
    const { convertTimeToTimezone } = inject('timezone');
    const state = reactive({
      btnloading:false,
		transitionValue: [],
      libraryList: [],
      tableLoading: false,
      dataSource: [],
      timeRange: null,
      pageInfo: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      searchForm: {
        ...initialParams,
      },
      transitionType: [],
      balanceType: [],
      visibleExport: false,
      columns: [
        {
          title: "类型",
          dataIndex: "account_type",
          key: "account_type",
        },
        {
          title: "交易名称",
          dataIndex: "title",
          key: "title",
        },
        
        {
          title: "业务单号",
          dataIndex: "bill_no",
          key: "bill_no",
        },
        {
          title: "数量",
          dataIndex: "changes",
          key: "changes",
        },
        {
          title: "变动情况",
          dataIndex: "modification",
          key: "modification",
        },
        {
          title: "交易时间",
          dataIndex: "created_at",
          key: "created_at",
        },
      ],
    });

    const handleExport = () => {
      state.btnloading = true
      let params = {
        ...state.searchForm,
      }
      request
        .put("/work_ai", "/user/shotstack/user/billing/export",params)
        .then((res) => {
          state.btnloading = false
          state.visibleExport = true;
        })
        .catch((err) => {
          state.btnloading = false
          message.error("操作失败");
        });
    };

    const handleTableChange = ({ current, pageSize }) => {
      console.log(current, pageSize);
      state.pageInfo.pageSize = pageSize;
      state.pageInfo.page = current;
      getTableList();
    };

    const handleDateChange = (date, dateString) => {
      state.searchForm.start_time = dateString[0];
      state.searchForm.end_time = dateString[1];
    };

    const handleChange = (val) => {
      state.searchForm.merchant_library_id = val;
    };
	
	const handleCascaderChange = (val) => {
		state.transitionValue = val
		let arr = []
		if(val?.length == 1){
			arr = state.transitionType.find(item=>item?.value == val[0])?.children?.map(item=>item?.value)
		} else if(val?.length == 2){
			arr = [val[1]]
		}
		if(val){
			state.searchForm.module_event = arr
		} else {
			state.searchForm.module_event = []
		}
	}

    const getTableList = () => {
      let params = {};
      state.tableLoading = true;
      Object.assign(params, state.pageInfo);
      Object.assign(params, state.searchForm);
      state.transitionType = [];
      state.balanceType = [];
      request
        .get("/work_ai", "/user/shotstack/user/billing/list", params)
        .then((res) => {
          state.dataSource = res.result.data;
          state.pageInfo.total = res?.result?.total;
          for (let key in res.result.account_type_list) {
            if(key!='video'){
              state.balanceType.push({
              label: res.result.account_type_list[key],
              value: key,
            });
            }
          }
          res?.result?.event_list?.map(item=>{
			  let obj = {}
			  obj.value = item?.key
			  obj.label = item?.title
			  obj.children = []
			  item?.item?.map(second_item=>{
				  obj.children.push({
					  label: second_item?.title,
					  value: second_item?.key,
				  })
			  })
			  state.transitionType.push(obj)
		  })
          state.tableLoading = false;
        })
        .catch((err) => {
          state.tableLoading = false;
        });
    };

    const queryThis = (type) => {
      if (type == "query") {
        getTableList();
      } else {
        state.pageInfo = {
          page: 1,
          pageSize: 10,
          total: 0,
        };
        state.searchForm = {
          ...initialParams,
        };
        state.timeRange = null;
        getTableList();
      }
    };

    const getLibraryList = () => {
      let params = {
        page: 1,
        pageSize: 100,
      };
      request
        .get("/work_ai", "/user/shotstack/library/withGroup/list", params)
        .then((res) => {
          state.libraryList = res.result;
        });
    };

    getTableList();
    getLibraryList();

    return {
      ...toRefs(state),
      handleTableChange,
      getTableList,
      queryThis,
      handleDateChange,
      handleChange,
      handleExport,
	    handleCascaderChange,
      convertTimeToTimezone
    };
  },
});
</script>

<style lang="less" scoped>
.form_item {
  margin-left: 10px;
  width: 200px;

  &:nth-child(1) {
    margin-left: 0;
  }
}

.export {
  text-align: right;
  margin-bottom: 10px;
}
</style>
